<?php 
namespace Emos\Field;

use Emos\Common;

class Choice extends AbstractControl {
    protected $items = array();
    protected $layout;
    
    protected $firstByDefault = true;
    
    public function __construct($items, $layout='select') {
        $this->items = $items;
        $this->layout = $layout;
    }
    
    public function setFirstByDefault($firstByDefault) {
        $this->firstByDefault = $firstByDefault;
        return $this;
    }

    public function validate() {            
        $post = $this->getPost();
        
        if(in_array($post, array_keys($this->items))) {            
            return true;
        }
        else {
            $this->error = Common::t('nothing chosen');            
            return false;
        }
    }    
    
    public function html() {
        $html = '';
        
        $curValue = $this->value;
                
        if($this->firstByDefault && ($curValue === null)) {
            reset($this->items);
            $curValue = key($this->items);            
        }
        
        if($this->layout == 'radio' || $this->layout == 'radio_horizontal') {
            foreach($this->items as $value => $label) {
                $s = ($value === $curValue) ? ' checked' : '';
                $html .= "<input name='{$this->htmlName}' type='radio' value='".Common::plain($value)."'{$s}>".Common::plain($label);
                $html .= ($this->layout == 'radio_horizontal') ? ' &nbsp; ' : '<br>';                
            }          
        }
        else {
            $html .= "<select name='{$this->htmlName}'>";
            foreach($this->items as $value => $label) {
                $s = ($value == $curValue) ? ' selected' : '';
                $html .= "<option value='".Common::plain($value)."'{$s}>".Common::plain($label)."</option>";
            }
            $html .= "</select>";              
        }
        
        return $html;
    }
    
    public function getFake() {        
        $keys = array_keys($this->items);
        $n = rand(0, count($this->items)-1);
        $k = $keys[$n];
        
        return array(
            $this->dbName => "'".$this->escapeSqlStr($this->items[$k])."'"
        );
    }   
}